<script setup lang="ts">
import { onMounted, ref } from "vue";
import { showFailToast, showSuccessToast } from "vant";
import "vant/es/toast/style";
import Hls from "hls.js";

defineOptions({
  name: "TpLinkVideo",
});

// 状态管理
const videoRef = ref<HTMLVideoElement | null>(null);
const isPlaying = ref(false);
const playScale = ref(1); // 默认1倍速
const isLoading = ref(false);
const hasError = ref(false);
const errorText = ref("");
let triggerTime = ref("");
let hls = new Hls();

// 播放器实例
let player: any = null;
let playInfo: any = null;

// 记录全局播放信息，确保重建播放器时可以使用
const storePlayInfo = (info: any) => {
  playInfo = {
    url: info.url,
    startTime: info.startTime,
    endTime: info.endTime,
    userId: info.userId,
  };
};

// 获取TPLink视频API数据
const handleSuccessReq = async (): Promise<void> => {
  try {
    // 从URL参数获取视频信息
    const urlParams = new URLSearchParams(window.location.search);
    const playUrl1 = decodeURIComponent(urlParams.get("playUrl1"));
    const playUrl2 = decodeURIComponent(urlParams.get("playUrl2"));
    const playUrl3 = decodeURIComponent(urlParams.get("playUrl3"));
    const playUrl4 = decodeURIComponent(urlParams.get("playUrl4"));
    const playUrl5 = decodeURIComponent(urlParams.get("playUrl5"));
    const startTime = urlParams.get("startTime");
    const endTime = urlParams.get("endTime");
    const userId = urlParams.get("userId");
    triggerTime.value = urlParams.get("triggerTime");
    const playUrl = `${playUrl1}${playUrl2}${playUrl3}${playUrl4}${playUrl5}`;

    // 检查必要参数是否存在
    if (!playUrl || !startTime || !endTime || !userId) {
      showFailToast("视频播放信息不完整");
      hasError.value = true;
      errorText.value = "视频播放信息不完整";
      return;
    }

    // 设置播放信息
    const videoPlayInfo = {
      url: playUrl,
      endTime: parseInt(endTime),
      startTime: parseInt(startTime),
      userId: parseInt(userId),
    };

    console.log("----------------");
    console.log("播放URL:", videoPlayInfo.url);
    console.log("开始时间:", videoPlayInfo.startTime);
    console.log("结束时间:", videoPlayInfo.endTime);
    console.log("用户ID:", videoPlayInfo.userId);
    console.log("打秤时间:", triggerTime);
    console.log("----------------");

    // 判断两个时间戳间隔具体几分钟
    const timeDiff = videoPlayInfo.endTime - videoPlayInfo.startTime;
    const minutes = Math.floor(timeDiff / 60 / 1000);
    console.log("时间间隔:", minutes);

    loadVideo(videoPlayInfo);
  } catch (error) {
    console.error("获取视频信息失败", error);
    showFailToast("获取视频信息失败");
    hasError.value = true;
    errorText.value = "获取视频信息失败";
  }
};

/**
 * 加载视频
 * @param playInfo 视频播放参数
 */
const loadVideo = (playInfo: any): void => {
  if (!playInfo) return;

  isLoading.value = true;
  hasError.value = false;
  errorText.value = "";

  // 存储播放信息
  storePlayInfo(playInfo);

  console.log("开始加载视频:", playInfo);

  // 检查是否已经加载SDK
  if (window["tums-player"]) {
    console.log("SDK已加载，直接初始化播放器");
    initPlayer(playInfo);
    return;
  }

  // 加载TP-Link SDK
  loadTpLinkSdk(playInfo);
};

/**
 * 加载TP-LINK SDK
 * @param playInfo 视频播放参数
 */
const loadTpLinkSdk = (playInfo: any): void => {
  // 先移除可能存在的旧script
  const oldScript = document.getElementById("tplink-player-sdk");
  if (oldScript) {
    document.body.removeChild(oldScript);
  }

  // 动态加载TP-LINK SDK
  const script = document.createElement("script");
  script.id = "tplink-player-sdk";
  script.src =
    "https://smbcloud.tp-link.com.cn/static/tums-player/tums-player.umd.min.js";

  // SDK加载成功回调
  script.onload = () => {
    console.log("SDK加载成功");
    initPlayer(playInfo);
  };

  // SDK加载失败回调
  script.onerror = (e) => {
    console.error("SDK加载失败", e);
    hasError.value = true;
    errorText.value = "无法加载播放器SDK，请检查网络连接";
    isLoading.value = false;
    showFailToast("无法加载播放器SDK");
  };

  // 将脚本添加到文档
  document.body.appendChild(script);
};

/**
 * 初始化播放器
 * @param playInfo 视频播放参数
 */
const initPlayer = (playInfo: any): void => {
  // 获取播放器容器
  const container = document.getElementById("video-container");
  if (!container) {
    hasError.value = true;
    errorText.value = "找不到播放器容器";
    isLoading.value = false;
    return;
  }

  if (!window["tums-player"]) {
    hasError.value = true;
    errorText.value = "播放器SDK加载失败";
    isLoading.value = false;
    console.error("无法找到 tums-player");
    return;
  }

  const { url, endTime, startTime, userId } = playInfo;
  try {
    // 初始化播放器
    const TumsPlayer = window["tums-player"].default;
    player = new TumsPlayer(container, {
      type: "relay", // 协议类型，rtsp/relay
      url: url, // 取流地址
      pluginPath: "https://smbcloud.tp-link.com.cn/static",
      streamType: "sdvod",
      autoplay: true,
      eventType: [1, 2],
      startTime: startTime, // 跳转到指定时间开始回放
      endTime: endTime,
      userId: userId,
      scale: playScale.value, // 使用当前倍速
    });

    // 标记播放状态
    isPlaying.value = true;

    // 监听播放器加载完成事件
    player.on("ready", function (evt: any) {
      console.log("播放器加载完成", player.getPlaybackTime());
      isLoading.value = false;
      showSuccessToast("播放器加载完成");
    });

    // 监听播放器错误事件
    player.on("error", function (e: any) {
      console.error("播放器错误", e);
      hasError.value = true;
      isLoading.value = false;
      errorText.value = "播放错误，可能达到带宽限制";
      showFailToast("播放错误，可能达到带宽限制");
    });
  } catch (error) {
    console.error("初始化播放器实例失败", error);
    hasError.value = true;
    isLoading.value = false;
    errorText.value = "初始化播放器实例失败";
    showFailToast("初始化播放器实例失败");
  }
};

/**
 * 播放/暂停切换
 */
const togglePlay = () => {
  if (!player) return;

  try {
    console.log("当前播放状态:", isPlaying.value);

    if (isPlaying.value) {
      // 当前是播放状态，需要暂停
      player.pause();
      // 立即更新UI状态
      isPlaying.value = false;
      console.log("已执行暂停操作");
    } else {
      // 当前是暂停状态，需要播放
      player.play();
      // 立即更新UI状态
      isPlaying.value = true;
      console.log("已执行播放操作");
    }
  } catch (error) {
    console.error("播放/暂停操作失败", error);
    showFailToast("播放/暂停操作失败");

    // 尝试通过API获取真实播放状态
    if (player && player.isPlaying) {
      try {
        const realPlayingState = player.isPlaying();
        console.log("获取到真实播放状态:", realPlayingState);
        isPlaying.value = realPlayingState;
      } catch (e) {
        console.error("获取播放状态失败", e);
      }
    }
  }
};

/**
 * 向前快进10秒
 */
const forwardTenSeconds = () => {
  if (!player) return;

  try {
    // 获取当前播放时间（毫秒）
    const currentTime = player.getPlaybackTime();
    // 计算新时间（当前时间 + 10秒）
    const newTime = currentTime + 10000;

    // 设置新的播放时间
    player.setPlaybackConfig({
      startTime: newTime,
    });

    console.log("向前快进10秒", { currentTime, newTime });
    showSuccessToast("已前进10秒");
  } catch (error) {
    console.error("快进操作失败", error);
    showFailToast("快进操作失败");
  }
};

/**
 * 向后倒退10秒
 */
const backwardTenSeconds = () => {
  if (!player) return;

  try {
    // 获取当前播放时间（毫秒）
    const currentTime = player.getPlaybackTime();
    // 计算新时间（当前时间 - 10秒，不小于0）
    const newTime = Math.max(0, currentTime - 10000);

    // 设置新的播放时间
    player.setPlaybackConfig({
      startTime: newTime,
    });

    console.log("向后倒退10秒", { currentTime, newTime });
    showSuccessToast("已后退10秒");
  } catch (error) {
    console.error("倒退操作失败", error);
    showFailToast("倒退操作失败");
  }
};
// 组件卸载前清理资源
const cleanupPlayer = () => {
  if (player) {
    try {
      // 尝试销毁播放器
      player.destroy && player.destroy();
    } catch (e) {
      console.error("销毁播放器失败", e);
    }
    player = null;
  }
};
/**
 * 设置播放倍速
 * @param speed 播放倍速值 (1, 2, 4)
 */
const setPlaybackSpeed = (speed: 1 | 2 | 4) => {
  if (!player) {
    showFailToast("播放器未初始化");
    return;
  }

  try {
    // 直接更新倍速状态
    playScale.value = speed;

    // 获取当前播放信息，用于恢复播放
    let currentTime = 0;

    try {
      currentTime = player.getPlaybackTime();
      // 不再保存当前播放状态，切换倍速后总是播放
      console.log(`准备切换到${speed}倍速, 当前时间:${currentTime}`);
    } catch (e) {
      console.warn("获取播放信息失败", e);
    }

    // 简单的方法：直接清理掉旧播放器，创建新的
    try {
      if (player.destroy) {
        player.destroy();
      }
      player = null;
    } catch (e) {
      console.warn("清理旧播放器失败", e);
    }

    // 显示加载状态
    isLoading.value = true;

    // 确保playInfo存在
    if (!playInfo) {
      isLoading.value = false;
      showFailToast("播放信息丢失，请刷新页面");
      return;
    }

    // 重新初始化播放器
    const container = document.getElementById("video-container");
    if (!container) {
      isLoading.value = false;
      showFailToast("找不到播放器容器");
      return;
    }

    // 清空容器
    container.innerHTML = "";

    // 创建新的播放器实例
    setTimeout(() => {
      try {
        const TumsPlayer = window["tums-player"].default;

        // 使用简单配置创建新播放器，并始终自动播放
        player = new TumsPlayer(container, {
          type: "relay",
          url: playInfo.url,
          pluginPath: "https://smbcloud.tp-link.com.cn/static",
          streamType: "sdvod",
          autoplay: true, // 总是自动播放
          eventType: [1, 2],
          startTime: currentTime, // 从当前时间继续播放
          endTime: playInfo.endTime,
          userId: playInfo.userId,
          scale: speed, // 使用新的倍速
        });

        // 监听播放器事件
        player.on("ready", () => {
          console.log(`播放器已就绪，倍速已设为${speed}x，将自动播放`);
          isLoading.value = false;

          // 切换倍速后总是设置为播放状态
          isPlaying.value = true;

          // 再次尝试播放，确保播放状态
          try {
            player.play();
          } catch (e) {
            console.warn("额外播放尝试失败", e);
          }

          showSuccessToast(`已切换到${speed}倍速播放`);
        });

        player.on("error", (e) => {
          console.error("播放器错误", e);
          isLoading.value = false;
          hasError.value = true;
          errorText.value = "播放器加载失败";
          showFailToast("播放器加载失败");
        });

        // 监听播放状态
        player.on("play", () => {
          console.log("播放器事件: 播放");
          isPlaying.value = true;
        });

        player.on("pause", () => {
          console.log("播放器事件: 暂停");
          isPlaying.value = false;
        });
      } catch (error) {
        console.error("创建播放器失败", error);
        isLoading.value = false;
        hasError.value = true;
        errorText.value = "创建播放器失败";
        showFailToast("创建播放器失败");
      }
    }, 300); // 给一个短暂的延迟，确保DOM操作完成
  } catch (error) {
    console.error("设置倍速失败", error);
    isLoading.value = false;
    showFailToast("设置倍速失败");
  }
};

// 重新播放视频
const handleReplayVideo = () => {
  cleanupPlayer();
  handleSuccessReq();
};

// 组件挂载时初始化
onMounted(() => {
  handleSuccessReq();
});
</script>

<template>
  <div class="tp-link-video">
    <div class="video-player">
      <div id="video-container" class="player-container" />

      <!-- 加载状态 -->
      <div v-if="isLoading" class="player-overlay">
        <van-loading type="spinner" color="#1989fa" />
        <span class="loading-text">视频加载中，请稍等...</span>
      </div>

      <!-- 错误状态 -->
      <div v-if="hasError" class="player-overlay">
        <van-icon name="warning-o" size="40" color="#ee0a24" />
        <span class="error-text">{{ errorText }}</span>
      </div>
    </div>

    <div class="video-title">
      <span>预警前后1分钟现场视频</span>
      <span v-if="triggerTime">打秤时间:{{ triggerTime }}</span>
    </div>

    <!-- 视频控制栏 -->
    <div class="video-controls">
      <div class="control-buttons">
        <van-button
          class="control-button"
          type="primary"
          plain
          size="small"
          :disabled="!player"
          @click="backwardTenSeconds"
        >
          <van-icon name="replay" />后退10s
        </van-button>

        <van-button
          type="primary"
          class="control-button"
          plain
          :disabled="!player"
          @click="togglePlay"
        >
          <van-icon :name="isPlaying ? 'pause' : 'play'" />
          {{ isPlaying ? "暂停" : "播放" }}
        </van-button>

        <van-button
          class="control-button"
          type="primary"
          plain
          size="small"
          :disabled="!player"
          @click="forwardTenSeconds"
        >
          前进10s
          <van-icon name="replay" class="control-button-icon" />
        </van-button>
      </div>
    </div>

    <!-- 倍速控制 -->
    <div class="speed-controls">
      <div class="speed-title">播放倍速:</div>
      <div class="speed-buttons">
        <van-button
          class="speed-button"
          :type="playScale === 1 ? 'primary' : 'default'"
          :plain="playScale !== 1"
          size="small"
          :disabled="!player"
          @click="setPlaybackSpeed(1)"
        >
          1x
        </van-button>

        <van-button
          class="speed-button"
          :type="playScale === 2 ? 'primary' : 'default'"
          :plain="playScale !== 2"
          size="small"
          :disabled="!player"
          @click="setPlaybackSpeed(2)"
        >
          2x
        </van-button>

        <van-button
          class="speed-button"
          :type="playScale === 4 ? 'primary' : 'default'"
          :plain="playScale !== 4"
          size="small"
          :disabled="!player"
          @click="setPlaybackSpeed(4)"
        >
          4x
        </van-button>
      </div>
    </div>

    <div class="controls">
      <van-button type="primary" block @click="handleReplayVideo"
        >重新播放视频</van-button
      >
    </div>
  </div>
</template>

<style scoped>
.tp-link-video {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.video-player {
  width: 100%;
  height: 400px;
  background-color: #000;
  position: relative;
  margin-bottom: 8px;
}

.player-container {
  width: 100%;
  height: 100%;
}

.player-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 10;
}

.loading-text,
.error-text {
  font-size: 16px;
  color: #fff;
  margin-top: 16px;
}

.video-controls {
  padding: 8px 16px;
  background-color: #f8f8f8;
  border-radius: 8px;
  margin-bottom: 8px;
}

.control-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.control-button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 86px;
  height: 30px;
  font-size: 12px;
  margin: 0 4px;
}

.speed-controls {
  padding: 8px 16px;
  background-color: #f8f8f8;
  border-radius: 8px;
  margin-bottom: 16px;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.speed-title {
  font-size: 14px;
  color: #333;
  margin-right: 16px;
  white-space: nowrap;
}

.speed-buttons {
  display: flex;
  flex: 1;
  justify-content: space-around;
}

.speed-button {
  width: 60px;
  height: 30px;
  font-size: 14px;
  font-weight: bold;
}

.controls {
  padding: 16px;
}

.control-button-icon {
  transform: rotate(180deg);
}

.video-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #aaa;
  padding: 0 10px;
}
</style>
